package com.zdf.license.verify.aspect;

import com.zdf.license.core.model.LicenseResult;
import com.zdf.license.verify.annotation.VLicense;
import com.zdf.license.verify.config.LicenseVerifyProperties;
import com.zdf.license.verify.model.LicenseVerifyManager;
import lombok.AllArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;

import java.lang.reflect.Method;

/**
 * 切面授权注解
 * 请求特定接口时候触发授权验证
 */
@Aspect
@AllArgsConstructor
public class VLicenseAspect implements Ordered {

    private final LicenseVerifyProperties properties;

    /**
     * 这里只是校验证书是否已经安装
     */
    @Around("@annotation(com.zdf.license.verify.annotation.VLicense)")
    public Object innerAround(ProceedingJoinPoint point) throws Throwable
    {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        VLicense vLicense = method.getAnnotation(VLicense.class);
        if (vLicense == null) {
            return point.proceed();
        }
        LicenseVerifyManager licenseVerifyManager = new LicenseVerifyManager();
        LicenseResult verifyResult = licenseVerifyManager.verify(properties.getVerifyParam());
        if(!verifyResult.getResult()){
            throw new RuntimeException(verifyResult.getMessage());
        }
        return point.proceed();
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
